package com.kaibes.web.response;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class ResponseUtils {
    
    @Autowired
    private ObjectMapper objectMapper;
    
    public void write(int status, String code, String message, Object data) {
        write(ResponseFactory.body(data, status, code, message));
    }

    public void write(HttpServletResponse response, int status, String code, String message, Object data) {
        write(response, ResponseFactory.body(data, status, code, message));
    }
    
    public void write(ResponseEntity<?> entity) {
    	HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    	write(response, entity);
    }
    
    public void write(HttpServletResponse response, ResponseEntity<?> entity) {
    	response.setStatus(entity.getStatusCode().value());
    	HttpHeaders headers = entity.getHeaders();
    	headers.forEach((key, values)->{
    		values.forEach(value->{
    			response.addHeader(key, value);
    		});
    	});
    	if (entity.getBody() != null) {
            try {
                response.getWriter().write(objectMapper.writeValueAsString(entity.getBody()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    	try {
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}
